package com.yc.d0415;

import java.util.ArrayList;
import java.util.List;

public class 生产者与消费者模式 {

    public static void main(String[] args) {
        Factory factory = new Factory();
        Thread t = new Thread(() -> {
            try {
                factory.product();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
        for (int i = 0; i < 10; i++) {
            Thread t1 = new Thread(() -> {
                try {
                    factory.consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "张三" + i);
            t1.start();
        }


    }
}

class Factory {
    List<Object> list = new ArrayList<>();
    // 生产  同步方法
    // 如果是实例方法, 锁定的对象就是当前对象 => this
    // 如果是静态方法, 锁定的对象就是当前类对象 => Xxxx.class
    public synchronized void product() throws InterruptedException {
        int i = 0;
        while (list.isEmpty()) {
            System.out.println("开始生产!");
            for (int j = 0; j < 10; j++) {
                list.add("产品" + i++);
                Thread.sleep(100);
            }
            System.out.println("生产结束!");
            // 通知其他线程
            this.notifyAll();
            // 等待
            this.wait();
        }
    }

    // 消费
    public void consume() throws InterruptedException {
        a: while (true) {
            Thread.sleep((long) (Math.random()* 200));
            synchronized (this) {
                while (list.isEmpty() == false) {
                    final String name = Thread.currentThread().getName();
                    System.out.println(name + " 购买产品 " + list.remove(0));
                    continue a;
                }
                this.notifyAll();
                this.wait();
            }
        }
    }

}

